<?php
/**
 * Created by PhpStorm.
 * FileName: Appointment.class.php
 * User: Administrator
 * Date: 2018/4/16
 * Time: 10:02
 */

namespace Api\Controller;

use Admin\Model\OrderModel;
use Admin\Model\TripModel;
use Admin\Model\UserModel;
use Admin\Model\UserSignModel;
use Common\Lib\Util\LogUtil;

class UserController extends ApiController {

    private $userModel;
    private $userSignModel;
    private $tripModel;
    private $orderModel;

    public function __construct() {
        parent::__construct();
        $this->userModel = new UserModel();
        $this->userSignModel = new UserSignModel();
        $this->tripModel = new TripModel();
        $this->orderModel = new OrderModel();
    }

    // 个人信息
    public function index() {
        $user_id = I('user_id');
        $user = $this->userModel->where(array('id' => $user_id))->find();
        $user['level_label'] = $this->userLevelInfo['user_level_label'];
        $user['signDays'] = $this->getSignDays($user_id);
        $user['isSigned'] = $this->isSigned($user_id);
        $user['statistics'] = $this->statisticsTrip($user_id);
        $this->callBack('用户信息！',$this->SUCCESS_CODE,$user);
    }

    // 用户登录
    public function login() {
        $appId = C('appId');
        $appSecret = C('appSecret');
        $code = I('code');
        $apiUrl = sprintf('https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',$appId,$appSecret,$code);
        $result = file_get_contents($apiUrl);
        $data = json_decode($result,true);
        if ($data['errcode'] == 0) {
            return $this->add($data);
        }
        $this->callBack($data['errMsg'],$this->ERROR_CODE);
    }

    // 添加微信用户
    private function add($result) {
        $userInfo = $this->getUserInfo($result);
        if (!$userInfo || !$userInfo['openId']) {
            LogUtil::info('session_key及openid信息:');
            LogUtil::info($result);
            LogUtil::info('userInfo信息:');
            LogUtil::info($userInfo);
            return $this->callBack('无效的openid信息！',$this->ERROR_CODE);
        }
        $row = $this->userModel->where(array('openid' => $result['openid']))->find();
        $userData = array(
            'user_name' => $userInfo['nickName'],
            'avatar' => $userInfo['avatarUrl'],
            'gender' => $userInfo['gender'],
            'openid' => $userInfo['openId'],
            'role_id' => C('DEFAULT_ROLE_ID'),
            'credit' => $this->sysConfig['level_0']
        );
        if ($row) {
            $rs = $this->userModel->update($userData,array('id' => $row['id']));
        } else {
            $rs = $this->userModel->add($userData);
        }
        if ($rs !== false) {
            $user_id = $row ? $row['id'] : $rs;
            $response = $this->userModel->where(array('id' => $user_id))->find();
            return $this->callBack('用户信息保存成功！',$this->SUCCESS_CODE,$response);
        }
        return $this->callBack('用户信息保存失败！',$this->ERROR_CODE);
    }

    // 解析用户信息
    private function getUserInfo($result) {
        vendor('wxCrypt.wxBizDataCrypt','','.php');
        $appId = C('appId');
        $iv = I('iv');
        $encryptedData = I('encryptedData');
        $sessionKey = $result['session_key'];
        $pc = new \WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            return json_decode($data,true);
        }
        return $errCode;
    }

    private function getSignDays($userId) {
        $sql = "select * from ( ";
        $sql .= "select @row_no:=@row_no+1 as row_no,@group_row:=if(@sign_date=DATE_FORMAT(date_add(FROM_UNIXTIME(add_time), interval -1 day),'%Y%m%d'),@group_row+1,1) as group_row, ";
        $sql .= "@sign_date:=FROM_UNIXTIME(add_time,'%Y%m%d') as sign_date,p.* from ";
        $sql .= "(select * from user_sign where user_id=".$userId." group by FROM_UNIXTIME(add_time,'%Y%m%d')) p, ";
        $sql .= "(select @row_no:=0,@group_row:=0,@sign_date:='') b ";
        $sql .= "order by add_time asc) a order by row_no desc limit 1";
        $result = M()->query($sql);
        $data = reset($result);
        $signDays = $data['group_row'];
        return $signDays ? $signDays : 0;
    }

    private function isSigned($userId) {
        $currentDate = date('Y-m-d');
        $data = array(
            'user_id' => $userId,
            'add_time' => array('between',sprintf('%s,%s',strtotime(sprintf('%s 00:00:00',$currentDate)),strtotime(sprintf('%s 23:59:59',$currentDate))))
        );
        $isSigned = $this->userSignModel->where($data)->count();
        return $isSigned > 0 ? true : false;
    }

    public function statisticsTrip($user_id) {
        $tripCount = $this->tripModel->where(array('user_id' => $user_id))->count();
        $successOrderCount = $this->orderModel->where(array('seller_id' => $user_id,'state' => array('in','8')))->count();
        $failOrderCount = $this->orderModel->where(array('seller_id' => $user_id,'state' => array('in','6')))->count();
        $canceledOrderCount = $this->orderModel->where(array('seller_id' => $user_id,'state' => array('in','5,7')))->count();
        $result = array(
            'tripCount' => $tripCount,
            'successOrderCount' => $successOrderCount,
            'failOrderCount' => $failOrderCount,
            'canceledOrderCount' => $canceledOrderCount
        );
        return $result;
    }

}